//
//  RichTextViewController.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/3/2.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit

class RichTextViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var webHeights: [CGFloat] = [0, 0 ,0]
    var paths: [String] = []
    var progress: Float = 0.0
    var tableView:UITableView!
    public var progressView: UIProgressView = {
        let progress: UIProgressView = UIProgressView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 1))
        progress.tintColor = .blue
        progress.trackTintColor = UIColor.clear
        return progress
    }()
    
    init(paths:[String], title: String) {
        super.init(nibName: nil, bundle: nil)
        self.paths = paths
        self.title = title
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        
        self.view.addSubview(self.progressView)
    }
    
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = Constant.bgViewColor
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView!.register(RichTextCell.self, forCellReuseIdentifier: "RichTextCell")
        self.view.addSubview(self.tableView!)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return paths.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: RichTextCell? = tableView.dequeueReusableCell(withIdentifier: "RichTextCell") as? RichTextCell
        cell?.selectionStyle = .none
        cell?.configure(paths[indexPath.row])
        cell?.webHeightClosure = {[weak self] height in
            if let `self` = self {
                DispatchQueue.main.async {
                    self.webHeights[indexPath.row] = height
                    self.tableView.beginUpdates()
                    self.tableView.endUpdates()
                }
            }
        }
        cell?.progressClosure = {[weak self] value in
            if let `self` = self {
                
            }
        }
        return cell!
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return webHeights[indexPath.row]
    }
}

